package com.example.readbook.UI.Act

import android.content.Intent
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import com.example.readbook.Adapter.BookAdapter
import com.example.readbook.Bean.BookBean
import com.example.readbook.R
import com.example.readbook.Sql.SqliteUtils
import com.example.readbook.UI.BaseUI.BaseActivity
import com.example.readbook.Utils.SpUtils
import com.example.readbook.Utils.StringUtils
import com.example.readbook.Utils.Utils
import com.yanzhenjie.permission.AndPermission
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : BaseActivity() {

    val mAdapter: BookAdapter by lazy {
        BookAdapter(mActivity, ArrayList<BookBean>())
    }

    override fun getLayoutResID(): Int {
        return R.layout.activity_main
    }

    override fun initView() {
        title = "爱阅读"
        initToggle()
        val manager = LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false)
        Act_Main_Recy.layoutManager = manager
        Act_Main_Recy.adapter = mAdapter
        val readAllBook = SqliteUtils.getInstence(mActivity).readAllBook()
        Log.e("yxs", "数组长度：${readAllBook.size}")
        mAdapter.updateList(readAllBook)
        requestPermission()
        supportActionBar?.setHomeButtonEnabled(true)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    override fun initListener() {

    }

    override fun initData() {

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_add, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.Add_Book -> {    //新增书籍
                if (!SpUtils.getBoolean(StringUtils.SD_Permission, false)) {
                    Utils.showToast("没有读取SD卡权限，无法添加书籍！")
                    return true
                }
                mAdapter.showAllDelete(false)
                startActivityForResult(Intent(mActivity, BookScanningActivity::class.java), 8)
                return true
            }
            android.R.id.home -> {  //点击标题栏菜单键 系统的ID
                if (mDrawerLayout.isDrawerOpen(Gravity.START)) {
                    mDrawerLayout.closeDrawer(Gravity.START)
                } else {
                    mDrawerLayout.openDrawer(Gravity.START)
                }
                return true
            }
        }
        return true
    }

    private fun requestPermission() {
        AndPermission.with(mActivity)
                .permission(StringUtils.SD)
                .onGranted {
                    SpUtils.putBoolean(StringUtils.SD_Permission, true)
                }
                .onDenied {
                    SpUtils.putBoolean(StringUtils.SD_Permission, false)
                }
                .start()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.e("yxs", "返回代码：" + resultCode)
        if (requestCode == 8 && resultCode == 9) {
            mAdapter.updateList(SqliteUtils.getInstence(mActivity).readAllBook())
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (mDrawerLayout.isDrawerOpen(Gravity.START)) {
            mDrawerLayout.closeDrawer(Gravity.START)
            return true
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mAdapter.isShowAll) {
                mAdapter.showAllDelete(!mAdapter.isShowAll)
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }


    /**
     * 绑定侧边框
     */
    private fun initToggle() {
        val toggle = ActionBarDrawerToggle(this, mDrawerLayout, R.string.app_name, R.string.app_name)
        mDrawerLayout.addDrawerListener(toggle)
        toggle.syncState()

        val params = mNavigation.getLayoutParams()

        params.width = Utils.getWindowWidght(this@MainActivity) - Utils.getWindowWidght(this@MainActivity) / 4
        mNavigation.layoutParams = params

        mNavigation.setNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.after_read -> {      //写读后感
                    if (SqliteUtils.getInstence(mActivity).readAllBookName().isNullOrEmpty()) {
                        Utils.showToast("你的书架上还没有书!")
                    } else {
                        startActivity(Intent(mActivity, WriteJournalEntryActivity::class.java))
                        mDrawerLayout.closeDrawer(Gravity.START)
                        it.isCheckable = false
                    }
                }
                R.id.look_read -> {     //看读后感
                    startActivity(Intent(mActivity, ReadJournalEntryActivity::class.java))
                    mDrawerLayout.closeDrawer(Gravity.START)
                    it.isCheckable = false
                }
            }

            false
        }
    }


}
